'''
Created on Jun 8, 2013

@author: Cihat Basol
'''

import logging
import time
import multiprocessing as mp

from rpyc.utils.server import ThreadedServer

from dexen.common import remoting, utils
from dexen import node
from dexen.node.worker import endpoint as worker_endpoint

#===============================================================================
# 
#===============================================================================
_workers = {} # worker_name : process
_server_addr = None
_job_name = None
_node_name = None
_max_workers = None

logger = logging.getLogger(__name__)
#===============================================================================
# 
#===============================================================================
class NodeEndPoint(remoting.BaseEndPoint):
    def on_connect(self):
        pass
    
    def on_disconnect(self):
        pass
    
    def start_worker(self, worker_name):
        if _workers.has_key(worker_name):
            return
        _workers[worker_name] = mp.Process(name=worker_name, 
                                           target=worker_endpoint.start, 
                                           args=(_server_addr, worker_name))
        _workers[worker_name].start()
    
    def stop_worker(self, worker_name):
        if not _workers.has_key(worker_name):
            return
        _workers[worker_name].terminate()
        del _workers[worker_name]

    def num_workers(self):
        return _max_workers

    def get_associated_job(self):
        return _job_name


#===============================================================================
# 
#===============================================================================
def init_dirs():
    node.create_dir(node.DEXEN_DIR)
    utils.del_tree(node.DEXEN_DIR)
    import os
    assert os.path.exists(node.DEXEN_DIR)


def start(server_addr, max_workers, job_name=None):
    global _server_addr, _job_name, _node_name, _max_workers

    #init_dirs()
    
    _server_addr = server_addr
    _max_workers = max_workers
    _job_name = job_name
    
    node_endpoint = ThreadedServer(NodeEndPoint, 
                                   protocol_config=remoting.DEFAULT_CONFIG)

    server_conn = remoting.connect(server_addr)
    my_addr = remoting.EndPointAddress(remoting.get_my_ip(), node_endpoint.port)
    _node_name = server_conn.root.register_node(my_addr)
    node_endpoint.logger = logging.getLogger(__name__+"."+_node_name)
    time.sleep(5)
    server_conn.close()
    node_endpoint.start()


